/*
 * @Author: aum
 * @Date: 2021-03-09 18:19:19
 * @LastEditors: aum
 * @LastEditTime: 2021-08-27 18:42:41
 * @Description: 文件描述
 * @FilePath: \vue3-hand-vant\src\store\modules\user.ts
 */
import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'
import store from '@/store'
import { SDSessionStorage } from '@/utils/cache'

import { AccountLoginModel } from '@/api/model/user'
import router from '@/router'
import { LOGIN__INFO, USER_INFO_KEY } from '@/enums/cache-enum'

@Module({ name: 'user', dynamic: true, namespaced: true, store })
class User extends VuexModule {
  private userInfoState: AccountLoginModel | null = null

  public get getUserInfoState(): AccountLoginModel {
    if (this.userInfoState) {
      return this.userInfoState
    } else {
      return SDSessionStorage.get(USER_INFO_KEY)
    }
  }

  @Mutation
  public commitUserInfoState(userInfo: AccountLoginModel): void {
    this.userInfoState = userInfo
    // 本地缓存userinfo
    SDSessionStorage.set(USER_INFO_KEY, userInfo)
  }

  @Action
  public async dispatchUserLogout() {
    SDSessionStorage.remove(LOGIN__INFO)
    SDSessionStorage.remove(USER_INFO_KEY)
    router.push('/tool/login')
  }
}

export const userStore = getModule<User>(User)
